package cn.bitkit.tools.file;

import lombok.Cleanup;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.configuration2.AbstractConfiguration;
import org.apache.commons.configuration2.YAMLConfiguration;
import org.apache.commons.configuration2.builder.fluent.Configurations;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 
 * @author changbo
 *
 */
@Slf4j
public class ConfigUtil {

	@SneakyThrows
	public static Map<String, String> readConfig(String fileName){
		Map<String, String> data = new HashMap<>();
		AbstractConfiguration config = null;
		if(fileName.endsWith(".properties")) {
			Configurations configs = new Configurations();
			config = configs.properties(ConfigUtil.class.getClassLoader().getResource(fileName));
		}
		if(fileName.endsWith(".yml")) {
			@Cleanup
			InputStream is = ConfigUtil.class.getClassLoader().getResourceAsStream(fileName);
			YAMLConfiguration yamlConfig = new YAMLConfiguration();
			yamlConfig.read(is);
			config = yamlConfig;
		}
		//读取数据
		if(config != null) {
			Iterator<String> keys = config.getKeys();
			while(keys.hasNext()) {
				String key = keys.next();
				data.put(key, config.getString(key));
			}
		}
		return data;
	}

}
